package com.mccraywebtech.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mccraywebtech.dao.GenericDAO;
import com.mccraywebtech.models.Contact;

@Repository("contactDAO")
public class ContactDAOImpl implements GenericDAO<Contact> {
	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * @return the sessionFactory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Override
	public void saveObject(Contact c) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(c);
		session.getTransaction().commit();
	}

	@Override
	public void updateObject(Contact c) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.update(c);
		session.getTransaction().commit();
	}

	@Override
	public void deleteObject(int id) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Contact.class);
		criteria.add(Restrictions.eq("id", id));
		Contact c = (Contact) criteria.uniqueResult();
		if (!c.toString().isEmpty()) {
			session.delete(c);
			session.getTransaction().commit();
		}
	}

	@Override
	public Contact getObject(int id) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Contact.class).add(
				Restrictions.eq("id", id));
		return (Contact) criteria.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Contact> getAllObjects() {
		// TODO Auto-generated method stub
		System.out.println("In dal...");
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Contact.class);
		return criteria.list();
	}

	@Override
	public Contact getByUsername(String username) {
		// TODO Auto-generated method stub
		return null;
	}
}
